/**
*  \file interpol_S16_S16.c
*
*  \brief Interpolation 16 bit signed nodes.
*
*  \author  Michael J. Hohmann <michael.hohmann@linde-mh.de>
*
*/

/*===============================================[ private includes  ]================================================*/
#define INTERPOL_S16_S16_LINKAGE
#include "interpol_s16_s16.h"
#include "../assertor/assertor.h"
#include "../saturated/scast.h"

/*===============================================[ private defines   ]================================================*/

/*===============================================[ private datatypes ]================================================*/

/*===============================================[ private variables ]================================================*/

/*===============================================[ public variables  ]================================================*/

/*===============================================[ private functions ]================================================*/

/*====================================================================================================================*/


S16 interpol_s16_s16(struct interpol_s16_s16_obj const* me, S16 value)
{
   ASSERTOR_PRE(NIL != me, "NULL is not allowed as object pointer.");
   {
      pal_size_t min = 0;
      pal_size_t max = me->count - 1;

      /* perform a binary search over table elements. */
      while ((max - min) > 1)
      {
         pal_size_t cursor = min + (max - min) / 2;
         if (me->x[cursor] > value)
         {
            max = cursor;
         }
         else
         {
            min = cursor;
         }
      }

      /* calculate interpolation of two immediate neighbour nodes */
      {
         S32 xval = value;

         S32 x1 = me->x[min];
         S32 y1 = me->y[min];

         S32 x2 = me->x[max];
         S32 y2 = me->y[max];

         S32 rv = ( ( (y2 - y1) * (xval-x1) ) / (x2 - x1)) + y1;

         ASSERTOR_POST( ( rv >= S16_MIN ) && ( rv <= S16_MAX ), "Result of computation does not fit into type of return value" );

         return saturated_cast_S32_S16( rv );
      }
   }
}

/***********************************************************************************************************************
*                          Copyright 2007-2018 Linde Material Handling. All rights reserved.                           *
***********************************************************************************************************************/
